package initialize

import (
	"fmt"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/locales/en"
	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	en_tran "github.com/go-playground/validator/v10/translations/en"
	zh_tran "github.com/go-playground/validator/v10/translations/zh"
	"reflect"
	"shop_srv_api/user_web/global"
	validator2 "shop_srv_api/user_web/validator"
	"strings"
)

/**
 * @Description
 * @Author huran
 * @Date
 * @Param
 * @return
 **/

// InitTrans 注册翻译器
func InitTrans(local string) (err error) {
	//修改gin框架的validator引擎属性，实现定制
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		v.RegisterTagNameFunc(func(field reflect.StructField) string {
			name := strings.SplitN(field.Tag.Get("json"), ",", 2)[0]
			if name == "-" {
				return ""
			}
			return name
		})
		zh := zh.New()
		en := en.New()
		//第一个参数是备用语言环境
		uni := ut.New(en, zh, en)
		global.Trans, ok = uni.GetTranslator(local)
		if !ok {
			return fmt.Errorf("uni.GetTranslator(%s)", local)
		}
		switch local {
		case "en":
			err := en_tran.RegisterDefaultTranslations(v, global.Trans)
			if err != nil {
				return err
			}
		case "zh":
			err := zh_tran.RegisterDefaultTranslations(v, global.Trans)
			if err != nil {
				return err
			}
		default:
			err := en_tran.RegisterDefaultTranslations(v, global.Trans)
			if err != nil {
				return err
			}
		}
		return err
	}
	return err
}

func InitValidatorEngine() {
	//注册验证器
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		_ = v.RegisterValidation("mobile", validator2.ValidateMobile)
		_ = v.RegisterTranslation("mobile", global.Trans, func(ut ut.Translator) error {
			return ut.Add("mobile", "{0}非法的手机号", true)
		}, func(ut ut.Translator, fe validator.FieldError) string {
			t, _ := ut.T("mobile", fe.Field())
			return t
		})
	}
}
